package com.cgnpc.scp.sri.laboratory.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.sri.laboratory.mybatis.entity.*;
import com.cgnpc.scp.sri.laboratory.mybatis.mapper.client.LaboratoryAnnualPlanMapper;
import com.cgnpc.scp.sri.laboratory.mybatis.mapper.client.LaboratoryAnnualPlanPhaseMapper;
import com.cgnpc.scp.sri.laboratory.mybatis.mapper.client.LaboratoryPhaseProgressMapper;
import com.cgnpc.scp.sri.laboratory.pojo.LaboratoryAnnualPlanPhaseVo;
import com.cgnpc.scp.sri.laboratory.service.LaboratoryAnnualPlanPhaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("laboratoryAnnualPlanPhaseService")
public class LaboratoryAnnualPlanPhaseServiceImpl implements LaboratoryAnnualPlanPhaseService{
    private static final Logger LOGGER = LoggerFactory.getLogger(LaboratoryAnnualPlanPhaseServiceImpl.class);

    @Autowired
    private LaboratoryAnnualPlanPhaseMapper laboratoryAnnualPlanPhaseMapper;

    @Autowired
    private LaboratoryAnnualPlanMapper laboratoryAnnualPlanMapper;

    @Autowired
    private LaboratoryPhaseProgressMapper laboratoryPhaseProgressMapper;

    @Autowired
    IBpmCenterService bpmCenterService;

    @Override
    public List<LaboratoryAnnualPlanPhase> getPhaseByPlanId(String planId) {
        return laboratoryAnnualPlanPhaseMapper.selectList(new QueryWrapper<LaboratoryAnnualPlanPhase>()
        .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_annualplanphase.file_id) as file_name")
        .eq("annual_plan_id",planId));
    }

    @Override
    public LaboratoryAnnualPlanPhaseVo stageInfo(String id) {

        LaboratoryAnnualPlanPhase phase = laboratoryAnnualPlanPhaseMapper.selectOne(new QueryWrapper<LaboratoryAnnualPlanPhase>()
        .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_annualplanphase.file_id) as file_name")
        .eq("id",id));

        List<LaboratoryAnnualPlanPhasePerson> persons = laboratoryAnnualPlanPhaseMapper.getPersonByPhaseId(id);
        phase.setPersons(persons);

        LaboratoryAnnualPlanPhaseVo vo = new LaboratoryAnnualPlanPhaseVo();
        vo.setPhase(phase);

        LaboratoryAnnualPlan info = laboratoryAnnualPlanMapper.selectOne(new QueryWrapper<LaboratoryAnnualPlan>()
                .select("*","concat(laboratory_name,'-', year) as plan_name")
                .eq("id",phase.getAnnualPlanId()));
        vo.setLaboratory(info);
        return vo;
    }

    @Override
    public LaboratoryAnnualPlanPhaseVo progressInfo(String id) {
        LaboratoryPhaseProgress progress = laboratoryPhaseProgressMapper.selectOne(new QueryWrapper<LaboratoryPhaseProgress>()
        .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_phase_progress.file_id) as file_name")
        .eq("id",id));

        LaboratoryAnnualPlanPhaseVo vo = stageInfo(progress.getPhaseId());
        vo.setProgress(progress);

        return vo;
    }

    @Transactional
    @Override
    public AjaxResult planStageSave(Map<String, Object> params) throws Exception {
        Map<String, Object> win = (Map<String, Object>)params.remove("stage");
        String phaseId = win.get("phaseId")+"";
        if(StringUtil.isNullOrSpace(phaseId) || "null".equals(phaseId)){
            return AjaxResult.error("phaseId can not be null");
        }
        LaboratoryAnnualPlanPhase planPhase = laboratoryAnnualPlanPhaseMapper.selectOne(new QueryWrapper<LaboratoryAnnualPlanPhase>()
                .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_annualplanphase.file_id) as file_name")
                .eq("id",phaseId));
        LaboratoryPhaseProgress progress = new LaboratoryPhaseProgress();
        String stageResultFileId = win.get("fileId")+"";
        String progressRemark = win.get("progressRemark")+"";
        String progressQuestion = win.get("progressQuestion")+"";
        progress.setProgressRemark(progressRemark);
        progress.setProgressQuestion(progressQuestion);
        progress.setFileId(stageResultFileId);
        if("1".equals(params.get("isModifyDraft"))){
            progress.setPhaseId(phaseId);
            //修改草稿的情况
            progress.setProcessStatus("2");
            laboratoryPhaseProgressMapper.update(progress, new UpdateWrapper<LaboratoryPhaseProgress>()
            .eq("phase_id", phaseId));
            return AjaxResult.success().put("data", planPhase);
        }
        progress.setId(IDHelper.uuid());
        progress.setPhaseId(planPhase.getId());
        progress.setProcessStatus("0");
        laboratoryPhaseProgressMapper.insert(progress);
        String folio = params.get("procChName") + "-" + planPhase.getCreateUser() + "-" +
                new SimpleDateFormat("yyyyMMdd").format(planPhase.getCreateTime());
        planPhase.setFolio(folio);
        laboratoryAnnualPlanPhaseMapper.updateById(planPhase);


        params.put("next_deal_name", JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        params.put("win", JSON.parseObject(JSON.toJSONString(win)));
        params.put("folio", folio);
        ApiResult apiResult = null;
        //判断是否为保存草稿
        params.put("appFormId", progress.getId());
        if("1".equals(params.get("isSaveDraft"))){
            if(!"1".equals(params.get("isModifyDraft")+"")){
                bpmCenterService.addDraft(params);
            }
        }else{
            LOGGER.info("流程启动---");
            apiResult = bpmCenterService.startProcess(params);
            LOGGER.info("result--{}" , apiResult);
        }
        return AjaxResult.success().put("data", planPhase);
    }

    /**********************************
     * 用途说明: 进展提交流程的审批操作（通过或驳回）
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    @Transactional
    public ApiResult stageSubmitProcess(Map<String, Object> params) throws Exception {
        // 流程除了启动环节，任意环节提交时均要保存流程实例id
        String procInstId = params.get("procInstId").toString();
        if (StringUtil.isNullOrSpace(procInstId)) {
            throw new ScpException("procInstId is missing.");
        }
        //判断是前进还是后退
        String flag = params.get("deal_answer").toString();
        ApiResult apiResult = null;
        // 根据环节名称判断当前处理逻辑
        String act_name = params.get("now_deal_act").toString();
        String formInstID = params.get("formInstID").toString();
        params.put("next_deal_name",JSONArray.parseArray(JSON.toJSONString(params.remove("next_deal_name"))));
        Object copygive = params.remove("copygive");
        if(copygive != null && !"".equals(copygive)){
            params.put("copygive",JSONArray.parseArray(JSON.toJSONString(copygive)));
        }
        if (!StringUtil.isNullOrSpace(act_name)
                && ("020".equals(act_name) || "030".equals(act_name) ||"010".equals(act_name))
        ) {
            LaboratoryPhaseProgress progress = laboratoryPhaseProgressMapper.selectOne(new QueryWrapper<LaboratoryPhaseProgress>()
                    .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_phase_progress.file_id) as file_name")
                    .eq("id",formInstID));
            progress.setProcInstId(procInstId);
            if ("1".equals(flag)) {
                if("030".equals(act_name)){
                    //最后一个环节
                    progress.setProcessStatus("1");
                    progress.setProcessFinalTime(new Date());

                    LaboratoryAnnualPlanPhase phase = laboratoryAnnualPlanPhaseMapper.selectOne(new QueryWrapper<LaboratoryAnnualPlanPhase>()
                            .select("*","(select file_center_file_name from tbl_common_fileupload tcf where tcf.file_center_file_id = tbl_sri_laboratory_annualplanphase.file_id) as file_name")
                            .eq("id",progress.getPhaseId()));
                    phase.setProgressRemark(progress.getProgressRemark());
                    phase.setProgressQuestion(progress.getProgressQuestion());
                    phase.setFileId(progress.getFileId());
                    laboratoryAnnualPlanPhaseMapper.updateById(phase);
                }
                //提交stageInfo
                apiResult = bpmCenterService.submitworklistitem(params);
            } else if ("2".equals(flag)) {
                //驳回
                apiResult = bpmCenterService.rollBackAction(params);
            }
            laboratoryPhaseProgressMapper.updateById(progress);
        } else {
            throw new ScpException("activity not found.");
        }
        return apiResult;
    }

    @Override
    public ApiResult deleteProcessDraft(Map<String, Object> params) throws Exception {
        String infoId = params.get("formno").toString();

        laboratoryPhaseProgressMapper.deleteById(infoId);

        return bpmCenterService.deleteMyDraft(params);
    }

}
